package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService{

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {

        //设计key的规则: 1,唯一性 2.可读性 3.灵活性 4.时效性
        String key = RedisKeys.VERIFY_CODE.join(phone);

        //存入到redis中
        template.opsForValue().set(key,code, RedisKeys.VERIFY_CODE.getTime(),
                TimeUnit.SECONDS);
    }
    @Override
    public String getVerifyCode(String phone){

        String key = RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);
    }

    @Override
    public String setToken(UserInfo user) {

        //1.创建token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //2.将token作为key,用户对象作为value 设置到redis中
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String value = JSON.toJSONString(user); //json格式字符串
        //3.有效时间30分钟
        template.opsForValue().set(key,value,
                RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {

        //判断token令牌是否有值
        if (!StringUtils.hasLength(token)){
            return null;
        }
        //通过以token为key,查redis缓存库得到用户对象user
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        //判断user是否有值,有值则已经登录
        if (template.hasKey(key)){
            String userStr = template.opsForValue().get(key);
            UserInfo info = JSON.parseObject(userStr,UserInfo.class);
            //重置token有效时间
            template.expire(key,RedisKeys.USER_LOGIN_TOKEN.getTime(),
                    TimeUnit.SECONDS);
            return info;
        }
        return null;
    }
}
